<template>
  <div>
    <h5 class="text-muted">当前任务：电子保函</h5>
    <el-form class="query-table-form" @submit.native.prevent :inline="true" :model="params">
      <el-form-item>
        <select-address
          v-model="params.address_code"
          :auto-top="true"
          @change="getData"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          placeholder="企业名称查询"
          :clearable="true"
          @change="getData"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.lender_idcard"
          placeholder="身份证号码查询"
          :clearable="true"
          @change="getData"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.corp_name"
          placeholder="经营者名称查询"
          :clearable="true"
          @change="getData"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-checkbox
          v-model="params.has_ele_fee"
          border
          :true-label="1"
          false-label=""
          @change="getData"
        >
          电表
        </el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
      </el-form-item>
    </el-form>

    <c-table border class="table-sm" v-loading="loading" :columns="tableColumns" :data="tableData">
      <template v-slot:address="scope">
        <div class="text-truncate" :title="scope.row.address">{{ scope.row.address }}</div>
      </template>

      <template v-slot:status="scope">
        <div class="badge" :class="`badge-${scope.row.statusStyle}`">
          {{ scope.row.statusLabel }}
        </div>
      </template>

      <template v-slot:creditStatus="scope">
        <div class="status-label" :class="`badge-${letterStyle[scope.row.gua_letter_status]}`">
          {{ enumCreditLetterStatus[scope.row.gua_letter_status] }}
        </div>
      </template>

      <template v-slot:bankStatus="scope">
        <div
          class="status-label"
          v-if="+scope.row.ele_letter_status < 1"
          :class="`badge-${letterStyle[scope.row.ele_letter_status]}`"
        >
          {{ enumBankLetterStatus[scope.row.ele_letter_status] }}
        </div>
        <el-popover placement="top-start" v-else title="银行项目经理" width="200" trigger="hover">
          <div>
            <div>{{ `姓名： ${scope.row.bank_approved_person || '-'};` }}</div>
            <div>{{ `电话： ${scope.row.bank_approved_person_mobile || '-'}` }}</div>
          </div>
          <div slot="reference">
            <div class="status-label" :class="`badge-${letterStyle[scope.row.ele_letter_status]}`">
              {{ enumBankLetterStatus[scope.row.ele_letter_status] }}
            </div>
          </div>
        </el-popover>
      </template>
    </c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="getData"
      ></el-pagination>
    </div>
    <letter-edit-dialog
      :visible.sync="visible"
      @success="closeGetData"
      :relatedData="related"
    ></letter-edit-dialog>
    <attach-cmpt :visible.sync="attachVisible" :customer-related-id="attachRelatedId"></attach-cmpt>
    <letter-view-dialog :visible.sync="printVisible" :relatedData="viewData"></letter-view-dialog>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { enumOrgClass, enumMainType } from '@/credit/plugins/enum'
import SelectAddress from '@/components/select/SelectAddress'
import LetterEditDialog from '@/credit/views/county/mission/components/LetterEditDialog'
import LetterViewDialog from '@/credit/views/county/mission/components/LetterViewDialog'
import AttachCmpt from '@/credit/views/city/program/Attach'
import { enumBankLetterStatus, enumCreditLetterStatus } from '@/credit/plugins/enumTown'
// import AttachView from '@/credit/components/AttachView'
const enumStatusStyle = {
  0: 'info',
  1: 'success',
  2: 'warning',
  3: 'danger',
}
const letterStyle = {
  0: 'info',
  1: 'warning',
  2: 'success',
  3: 'danger',
}
const enumStatusLabel = {
  0: '未审核',
  1: '已审核',
  2: '审核中',
  3: '未通过',
}

export default {
  components: {
    SelectAddress,
    AttachCmpt,
    // AttachView,
    LetterEditDialog,
    LetterViewDialog,
  },
  props: {},
  data() {
    return {
      printVisible: false,
      viewData: {},
      letterStyle,
      enumStatusStyle,
      enumCreditLetterStatus,
      enumBankLetterStatus,
      params: {
        index: 1,
        size: 10,
        lender_idcard: '',
        customer_name: '',
        corp_name: '',
        'claim_status.eq': 1,
        'is_approval.eq': 1,
        'submit_type.in': '1,2',
        'service_id.eq': '',
      },
      loading: false,
      visible: false,
      attachVisible: false,
      attachRelatedId: '',
      related: {},
      tableName: 'customer_related_view',
      tableData: [],
      totalCount: 0,
      tableColumns: [
        {
          attrs: { label: '主体名称', prop: 'customer_name', minWidth: '120px' },
          process: (v, row) => ({
            attrs: { class: 'project-history', attrs: { 'data-history': row.is_history } },
          }),
        },
        { attrs: { label: '地址', prop: 'address' }, slot: 'address' },
        {
          attrs: { label: '组织形式', prop: 'org_class', align: 'center' },
          process: v => enumOrgClass[v] || '-',
        },
        { attrs: { label: '贷款人', prop: 'corp_name', align: 'center' } },
        { attrs: { label: '联系电话', prop: 'mobile_no', align: 'center' } },
        { attrs: { label: '认领银行', prop: 'bank_name', align: 'center' } },
        { attrs: { label: '银行预审金额（万元）', prop: 'bank_approved_funds', align: 'center' } },
        { attrs: { label: '贷款年限（年）', prop: 'load_years', align: 'center' } },
        {
          attrs: { label: '是否联保', prop: 'gua_type', align: 'center' },
          process: v => enumMainType[v],
        },
        { attrs: { label: '复审状态', prop: 'statusLabel', align: 'center' }, slot: 'status' },
        { attrs: { label: '担保意向函状态', align: 'center' }, slot: 'bankStatus' },
        { attrs: { label: '联保函状态', align: 'center' }, slot: 'creditStatus' },
        {
          attrs: { label: '操作', align: 'center', minWidth: 150 },
          operations: [
            {
              content: '修改',
              icon: 'fa fa-edit',
              event: this.handleEdit,
              ifRender: row => +row.gua_letter_status < 2 || +row.ele_letter_status < 2,
            },
            {
              content: '查看',
              icon: 'fa fa-file',
              event: this.handleView,
            },
            // {
            //   content: '',
            //   icon: 'fa fa-files-o',
            //   event: this.handleUnion,
            //   ifRender: row => (+row.gua_letter_status === 0 && this.isUserTown) || (+row.gua_letter_status > 0)
            // },
            {
              content: '附件',
              icon: 'fa fa-file-image-o',
              event: this.hanleAttach,
            },
          ],
        },
      ],
    }
  },
  computed: {
    ...mapGetters(['user', 'userId', 'clientId', 'job']),
    isManager() {
      return ['org_credit_super', 'org_c_manage', 'org_r_emp', 'org_r_manage', 'org_corp'].includes(
        this.job
      )
    },
    isUserTown() {
      return this.user.orgRegionLever === 3
    },
  },
  watch: {
    $route(route) {
      if (route.name === 'missionPublic') {
        this.getData()
      }
    },
  },
  created() {
    if (this.isUserTown) {
      this.params['service_id.eq'] = this.clientId
    } else {
      this.params['recommend_service.eq'] = this.clientId
      this.params['gua_type.eq'] = 1
    }
    this.getData()
  },
  mounted() {},
  methods: {
    closeGetData() {
      this.visible = false
      this.$store.dispatch('getTaskCountTown')
      this.getData()
    },
    handleEdit(row) {
      this.related = { ...row }
      this.visible = true
    },
    handleView(row) {
      this.viewData = { ...row }
      this.printVisible = true
    },
    hanleAttach(row) {
      this.attachVisible = true
      this.attachRelatedId = row.customer_related_id
    },
    async getData() {
      const params = { ...this.params }
      const status = this.$route.query.status
      if (status !== undefined) {
        params['ele_letter_status.eq'] = status
        // if (+status === 1) {
        //   params['gua_letter_status.gte'] = status
        //   params['ele_letter_status.gte'] = status
        // } else {
        //   params['orWhere.gua_letter_status.eq'] = status
        //   params['orWhere.ele_letter_status.eq'] = status
        // }
      }
      if (!this.isManager) {
        params['orWhere.res_a.eq'] = this.userId
        params['orWhere.res_b.eq'] = this.userId
      }

      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, params, {
          create_time: 'desc',
        })
      )
      this.loading = false

      const data = (res && res.data) || {}
      this.totalCount = data.totalCount
      this.tableData = (data.data || []).map(item => {
        let status = 0
        if (
          +item.res_status === 0 &&
          +item.res_status_bus === 0 &&
          +item.res_status_risk === 0 &&
          +item.res_status_corp === 0
        ) {
          status = 0
        }
        if (
          +item.res_status === 1 &&
          +item.res_status_bus === 1 &&
          +item.res_status_risk === 1 &&
          +item.res_status_corp === 1
        ) {
          status = 1
        }
        if (
          +item.res_status === 1 &&
          (+item.res_status_bus === 0 || +item.res_status_risk === 0 || +item.res_status_corp === 0)
        ) {
          status = 2
        }
        if (
          +item.res_status === 2 ||
          +item.res_status_bus === 2 ||
          +item.res_status_risk === 2 ||
          +item.res_status_corp === 2
        ) {
          status = 3
        }
        item.statusLabel = enumStatusLabel[status] || '-'
        item.statusStyle = enumStatusStyle[status] || ''
        return item
      })
    },
  },
}
</script>
<style lang="scss" scoped>
.status-label {
  display: inline-block;
  padding: 0.25em 0.4em;
  font-size: 75%;
  font-weight: 700;
  line-height: 1;
  text-align: center;
  vertical-align: baseline;
  border-radius: 0.25rem;
  transition: color 0.15s;
}
</style>
